<?php

class AlbumAction extends CommonAction
{
	public function index()
	{
		$where = '';
		$parameter = array();
		$keyword = trim($_REQUEST['keyword']);
		$uname = trim($_REQUEST['uname']);
		$cid = (int)$_REQUEST['cid'];

		if(!empty($keyword))
		{
			$this->assign("keyword",$keyword);
			$parameter['keyword'] = $keyword;
			$where.=" AND a.title LIKE '%".mysqlLikeQuote($keyword)."%' ";
		}
		
		if(!empty($uname))
		{
			$this->assign("uname",$uname);
			$parameter['uname'] = $uname;
			$match_key = segmentToUnicodeA($uname,'+');
            $like_name = mysqlLikeQuote($uname);
            $where .= ' AND u.show_name LIKE \'%'.$like_name.'%\'';
		}
		
		if($cid > 0)
		{
			$this->assign("cid",$cid);
			$parameter['cid'] = $cid;
			$where .= " AND a.cid = $cid";
		}

		$model = M();

		if(!empty($where))
		{
			$where = 'WHERE' . $where;
			$where = str_replace('WHERE AND','WHERE',$where);
		}

		$sql = 'SELECT COUNT(DISTINCT a.id) AS tcount 
			FROM '.C("DB_PREFIX").'album AS a 
			LEFT JOIN '.C("DB_PREFIX").'user AS u ON u.uid = a.uid 
			'.$where;
		
		$count = $model->query($sql);
		$count = $count[0]['tcount'];

		$sql = 'SELECT a.*,ac.name AS cname,u.show_name   
			FROM '.C("DB_PREFIX").'album AS a 
			LEFT JOIN '.C("DB_PREFIX").'user AS u ON u.uid = a.uid 
			LEFT JOIN '.C("DB_PREFIX").'album_category AS ac ON ac.id = a.cid 
			'.$where.' GROUP BY a.id';
			
		$this->_sqlList($model,$sql,$count,$parameter,'a.id');
		//echo $sql; exit;
		$category_list = D("AlbumCategory")->order('sort asc,id asc')->findAll();
		$this->assign("category_list",$category_list);
		
		$this->display ();
		return;
	}
	public function add(){
		//获取标签分类
		/*
		$tag_cate=D('GoodsCategory')->where('parent_id=0')->order('sort')->field('cate_id,cate_name')->findAll();
		$tag_list = array();
		foreach($tag_cate as $k=>$v){
			$tag_list[$v['cate_id']] = D('GoodsCategory')->where('parent_id='.$v['cate_id'])->order('sort')->field('cate_id,cate_name')->findAll();
		}
		*/
		$user_list = D("User")->where('gid=7')->findAll();
		$category_list = D("AlbumCategory")->order('sort asc,id asc')->findAll();
		$this->assign("user_list",$user_list);
		$this->assign("category_list",$category_list);
		//$this->assign('tag_cate',$tag_cate);
		//$this->assign('tag_list',$tag_list);
		parent::add();
	}
	public function addalbum(){
		$user_list = D("User")->where('gid=7')->findAll();
		$category_list = D("AlbumCategory")->order('sort asc,id asc')->findAll();
		$this->assign("user_list",$user_list);
		$this->assign("category_list",$category_list);
		$this->display();
	}
	public function edit()
	{
		$id = intval($_REQUEST['id']);
		
		$cid = D('Album')->where('id='.$id)->getField('cid');
		/*
		if($cid==51 || $cid==52){
			//获取标签分类
			$type = array(51=>0,52=>1);
			$channel = array(51=>'态度标签',52=>'生活标签');
			$tag_list=array();
			$tag_cate = array(array('cate_id'=>$type[$cid],'cate_name'=>$channel[$cid]));
			$tag_list[$type[$cid]] = D('LifeTags')->where('type='.$type[$cid])->order('sort')->field('cate_id,cate_name')->findAll();
		}else{
			//获取标签分类
			$tag_cate=D('GoodsCategory')->where('parent_id=0')->order('sort')->field('cate_id,cate_name')->findAll();
			$tag_list = array();
			foreach($tag_cate as $k=>$v){
				$tag_list[$v['cate_id']] = D('GoodsCategory')->where('parent_id='.$v['cate_id'])->order('sort')->field('cate_id,cate_name')->findAll();
			}
		}
		
		//获取本身标签
		$tmp_tag = D('AlbumGoods')->where('album_id='.$id)->field('tag_id')->findAll();
		foreach($tmp_tag as $k=>$v){
			$album_tag[$k] = $v['tag_id'];
		}
		*/
		$user_list = D("User")->where('gid=7')->findAll();
		$category_list = D("AlbumCategory")->order('sort asc,id asc')->findAll();
		$this->assign("user_list",$user_list);
		$this->assign("category_list",$category_list);
		//$this->assign('tag_cate',$tag_cate);
		//$this->assign('tag_list',$tag_list);
		//$this->assign('album_tag',$album_tag);
		$this->assign('cid',$cid);
		parent::edit();
	}
	public function editPic(){
		$id = intval($_REQUEST['id']);
		//$share_list = D("Share")->where('rec_id='.$id)->order('sort asc,share_id asc')->findAll();
		//$share_list = D("Share")->table('tbl_share share, tbl_album_share ashare')->where('share.share_id = ashare.share_id and ashare.album_id='.$id)->order('sort asc,share_id asc' )->select();
		$sql = "select * from tbl_share share, tbl_album_share ashare where share.share_id = ashare.share_id and ashare.album_id=$id order by share.sort asc,share.share_id asc";
		$share_list = D("Share")->query($sql);
		
		$this->assign('albumid',$id);
		$this->assign('share_list',$share_list);
		
		$this->display('Album/uploadpic');
	}
	public function delpic(){
		$shareid = intval($_REQUEST['shareid']);
		$albumid = intval($_REQUEST['albumid']);
		$imgpath = D("Share")->where('share_id='.$shareid)->getField('index_img');
		unlink(RES_ROOT.$imgpath);
		D("AlbumShare")->where('share_id='.$shareid)->delete();
		D("Share")->where('share_id='.$shareid)->delete();
		D("Album")->query("update tbl_album set img_count = img_count-1 where id=".$albumid);
	}
	public function update()
	{
        $id = intval($_REQUEST['id']);
		//$_POST['is_flash'] = intval($_REQUEST['is_flash']);
		//$_POST['is_best'] = intval($_REQUEST['is_best']);
		//if($_POST['is_flash'] == 0)
		//	unset($_FILES['flash_img']);
			
		//if($_POST['is_best'] == 0)
		//	unset($_FILES['best_img']);
			
		$model = D ('Album');
		$album = $model->getById($id);
		
		if (false === $data = $model->create ()) {
			$this->error ( $model->getError () );
		}
		
		// 更新数据
		$list=$model->save($data);
		if (false !== $list)
		{
			//更新标签
			/*
			$del_res = D('AlbumGoods')->where('album_id = '.$id)->delete();
			if($del_res){
				$tag_list = $_POST['tag_list'];
				foreach($tag_list as $v){
					$tag_data['tag_id'] = $v;
					$tag_data['album_id'] = $id;
					D('album_goods')->add($tag_data);
				}
			}
			*/
			/*
			if($_POST['is_flash'] == 0 && !empty($album['flash_img']))
			{
				@unlink(STRENDS_ROOT.$album['flash_img']);
				$album['flash_img'] = '';
			}
			*/
			
			if($_POST['is_best'] == 0 && !empty($album['best_img']))
			{
				@unlink(STRENDS_ROOT.$album['best_img']);
				$album['best_img'] = '';
			}
							
			if($upload_list = $this->uploadImages())
			{
				foreach($upload_list as $upload_item)
				{
					$img = $upload_item['recpath'].$upload_item['savename'];
					if($upload_item['key'] == 'flash_img')
					{
						if(!empty($album['flash_img']))
							@unlink(STRENDS_ROOT.$album['flash_img']);
						
						D("Album")->where('id = '.$id)->setField('flash_img',$img);
					}
					elseif($upload_item['key'] == 'best_img')
					{
						if(!empty($album['best_img']))
							@unlink(STRENDS_ROOT.$album['best_img']);
						
						D("Album")->where('id = '.$id)->setField('best_img',PIC_ROOT.$img);
					}
				}
			}
			
			//Vendor("common");
			
			//FS('Share')->updateShare($album['share_id'],$_REQUEST['title'],$_REQUEST['content']);
			if($_REQUEST['cid'] != $album['cid'])
			{
				FDB::query('UPDATE '.FDB::table("album_share").' SET cid = '.$_REQUEST['cid'].' WHERE album_id = '.$id);
			}
			
			$this->saveLog(1,$id);
			$this->assign('jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		}
		else
		{
			//错误提示
			$this->saveLog(0,$id);
			$this->error (L('EDIT_ERROR'));
		}
	}
	public function insert(){
		$model = D ('Album');
		
		if (false === $data = $model->create ()) {
			$this->error ( $model->getError () );
		}
		//$tag_list = $_POST['tag_list'];
		$data['create_time'] = time();
		//$data['uid'] = $_SESSION['strends_shop_share'];
		
		// 更新数据
		$list=$model->data($data)->add();
		/*
		$tag_list = $_POST['tag_list'];
		foreach($tag_list as $v){
			$tag_data['tag_id'] = $v;
			$tag_data['album_id'] = $list;
			D('album_goods')->add($tag_data);
		}
		*/
		
		if (false !== $list)
		{
			if($upload_list = $this->uploadImages())
			{
				foreach($upload_list as $upload_item)
				{
					$img = $upload_item['recpath'].$upload_item['savename'];
					D("Album")->where('id = '.$id)->setField('best_img',PIC_ROOT.$img);
				}
			}

			//$this->assign('albumid',$list);
			//$this->display('Album/uploadpic');
			$this->saveLog(1,$id);
			$this->success (L('ADD_SUCCESS'));

		}else{
			//错误提示
			$this->saveLog(0,$id);
			$this->error (L('EDIT_ERROR'));
		}
	}
	public function insertalbum(){
		$model = D ('Album');
		$data = array();
		$data['cid'] = $_POST['cid'];
		$data['uid'] = $_POST['uid'];
		$url = $_POST['aurl'];
		
		include './public/phpQuery/phpQuery/phpQuery.php';  
			
		phpQuery::newDocumentFile($url); 
		phpQuery::$defaultCharset="euc-jp";
			
		$title  = pq('#img-content h2')->text();
		$data['title'] = mb_convert_encoding($title,'ISO-8859-1','utf-8');
		
		$time  = pq('#img-content .rich_media_meta_list #post-date')->text();			
		$data['create_time'] = strtotime($time);	
		
		$content  = pq('#img-content #js_content')->html();
		$content = mb_convert_encoding($content,'ISO-8859-1','utf-8');
				
		$content = str_replace('\"','"',$content);
		$content = str_replace('src','ll_src',$content);
		$content = str_replace('data-ll_src','src',$content);

		$c_arr = explode('<hr>',$content);
		$con_arr = explode('</p>',$c_arr[0]);
		array_shift($con_arr);

		$content = implode('</p>',$con_arr);

		preg_match_all("/<img([^>]*)\s*src=('|\")([^'\"]+)('|\")/", $content,$matches);

		$new_arr=array_unique($matches[0]);//去除数组中重复的值

		foreach($new_arr as $key=>$val){
			$i_arr = explode('src=',$new_arr[$key]);
			$ppp = $i_arr[1];
			$ppp=substr($ppp,1,strlen($ppp));  
			$pppp = substr($ppp,0,-1);  
			
			$path = $pppp.'&amp;wxfrom=5&amp;wx_lazy=1';
			//echo $path; exit;
			$picurl=get_name($path,$key);//这里处理图片并得到处理后的地址
			
			$content = str_replace($pppp,$picurl,$content);
		  
		}
		$data['content'] = $content;
		$tmp_content = strip_tags($content);
		$data['grid'] = mb_substr($tmp_content, 0, 120, 'utf-8');
		$data['status'] = 0;
		$data['is_index'] = 1;
		
		// 更新数据
		$list=$model->data($data)->add();
					
		if (false !== $list)
		{
			if($upload_list = $this->uploadImages())
			{
				foreach($upload_list as $upload_item)
				{
					$img = $upload_item['recpath'].$upload_item['savename'];
					D("Album")->where('id = '.$id)->setField('best_img',PIC_ROOT.$img);
				}
			}

			$this->saveLog(1,$id);
			$this->success (L('ADD_SUCCESS'));

		}else{
			//错误提示
			$this->saveLog(0,$id);
			$this->error (L('EDIT_ERROR'));
		}
	}
	public function remove()
	{
		@set_time_limit(0);
		if(function_exists('ini_set'))
			ini_set('max_execution_time',0);
	
		//删除指定记录
		//Vendor("common");
		$result = array('isErr'=>0,'content'=>'');
		$id = $_REQUEST['id'];
		if(!empty($id))
		{
			$name=$this->getActionName();
			$model = D($name);
			$pk = $model->getPk ();
			$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
            $ids = explode (',',$id);
            foreach($ids as $aid)
            {
                $album_data = D('Album')->where('id='.$aid)->find();
				if(!empty($album_data['best_img']))
					@unlink(RES_ROOT.$album_data['best_img']);
				D('Album')->where('id='.$aid)->delete();
                $share_sql = "select * from tbl_album_share ashare,tbl_share share where ashare.share_id=share.share_id and ashare.album_id=".$aid;
				$share_data = D('Share')->query($share_sql);
				foreach($share_data as $k=>$v){
					if(!empty($v['index_img']))
						@unlink(RES_ROOT.$v['index_img']);
					D("Share")->where('share_id='.$v['share_id'])->delete();
				}
				D("AlbumShare")->where('album_id='.$aid)->delete();
				//FS("Album")->deleteAlbum($aid,true);
            }

			$this->saveLog(1,$id);
		}
		else
		{
			$result['isErr'] = 1;
			$result['content'] = L('ACCESS_DENIED');
		}

		die(json_encode($result));
	}
	public function uploadpic(){
		$albumid = $_GET['albumid'];
		import("@.ORG.UploadFile");
		$upload = new UploadFile();
		$upload->maxSize = 3292200;
		$upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
		$id_path = getDirsById($albumid);
		$dir = RES_ROOT.'public/upload/share/'.$id_path.'/';
		if(!file_exists($dir)){
			createFolder($dir);
		}
		
		$upload->savePath = RES_ROOT.'public/upload/share/'.$id_path.'/';
		 
		$upload->imageClassPath = '@.ORG.Image';
		 
		 //设置上传文件规则
		$upload->saveRule = 'uniqid';
		
		 if (!$upload->upload()) {
			//捕获上传异常
			$this->error($upload->getErrorMsg());
		 } else {
			$uploadList = $upload->getUploadFileInfo();
			//import("@.ORG.Image");
			//Image::water($uploadList[0]['savepath'].$uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');
			$data = array();
			$data['index_img'] = 'public/upload/share/'.$id_path.'/'.$uploadList[0]['savename'];
			$data['rec_id'] = $albumid;
			$data['sort'] = 100;
			$data['uid'] = $_SESSION['strends_shop_share'];
			$data['create_time'] = time();
			$model = D ('Share');
			$list=$model->data($data)->add();
			$album_share = array();
			$album_share['album_id'] = $albumid;
			$album_share['share_id'] = $list;
			D('AlbumShare')->data($album_share)->add();
			D("Album")->query("update tbl_album set img_count = img_count+1 where id=".$albumid);
			$result=array('shareid'=>$list,'albumid'=>$albumid,'shareimg'=>'public/upload/share/'.$id_path.'/'.$uploadList[0]['savename']);
			die(json_encode($result));
		 }
	}
	public function textedit(){
		$aid = $_POST['aidArray'];
		$contentArray = $_POST['contentArray'];
		$pnameArray = $_POST['pnameArray'];
		$sortArray = $_POST['sortArray'];
		$model = D ('Share');
		$data = array();
		foreach($aid as $k=>$v){
			$data['share_id'] = $v;
			$data['title'] = $pnameArray[$k];
			$data['content'] = $contentArray[$k];
			$data['sort'] = $sortArray[$k];
			$data['create_time'] = time();
			// 更新数据
			$model->save($data);
		}
		$this->assign('jumpUrl', Cookie::get ( '_currentUrl_' ) );
		$this->success (L('EDIT_SUCCESS'));
	}
	public function makeImg(){
		$img = $_GET['loc'];
		$shareid = $_GET['shareid'];
		$albumid = $_GET['albumid'];
		$dir=dirname($img);
		$text_arr=D('share')->where('share_id='.$shareid)->find();
		$texts=explode("|^|",$text_arr['edit_text']);
		$resdomain = PIC_ROOT;
		
		$this->assign('dir',$dir);
		$this->assign('img',PIC_ROOT.$img);
		$this->assign('shareid',$shareid);
		$this->assign('albumid',$albumid);
		$this->assign('texts',$texts);
		$this->assign('resdomain',$resdomain);
		$this->display();
	}
	public function createimg(){
		if($_GET['issave']){
			$strsave = file_get_contents('php://input');
			$saveArr = explode('|',ltrim($strsave,'|^|'));
			$width = (int)$saveArr[1];
			$height = (int)$saveArr[2];
			$shareid = (int)$saveArr[4];
			$albumid = (int)$saveArr[3];
			$newPic = $saveArr[0];
			
			$data = array();
			$data['id'] = $albumid;
			$data['is_best'] = 1;
			$data['best_img'] = $newPic;
			$result = D('Album')->save($data);
			echo $result;
			exit;
		}
		mb_internal_encoding("UTF-8");
		$str = file_get_contents('php://input');
		if( $str=='' ) $str =  "w=remingbisjfdksd&p=/tpl/strends/tmp/1.jpg&p_s=&x=0&y=0&size=12&color=#000000&family=方正粗倩简体&fontLeading=0&linespacing=0";
		
		parse_str($str,$paraArr);
		$imgpath = substr($paraArr['imgpath'],strpos($paraArr['imgpath'],'public/upload/'));
		
		$txt = str_replace('+','%2B',$paraArr['text_input']); 	//解析时把成了%2B转换+,解码前应将+转换为%2B
		$txt = urldecode($txt);
		$font_size = $paraArr['font_size'];
		$font_color = $paraArr['font_color'];
		$space = $paraArr['spacing'];
		$linespacing = $paraArr['linespacing'];
		$txt_x = $paraArr['font_x'];
		$txt_y = $paraArr['font_y'];
		$font = $paraArr['selectFont'];
		
		$area_x = intval($paraArr['area_x']);
		$area_y = intval($paraArr['area_y']);
		$area_w = intval($paraArr['area_w']);
		$area_h = intval($paraArr['area_h']);
		$shareid= intval($paraArr['shareid']);
		$albumid= intval($paraArr['albumid']);
		//if($linespacing<2) $linespacing = 1;
		$txt_arr = explode('|^|',$txt);
		$font_size_arr = explode('|^|',$font_size);
		$font_color_arr = explode('|^|',$font_color);
		$spacing_arr = explode('|^|',$space);
		$linespacing_arr = explode('|^|',$linespacing);
		$txt_x_arr = explode('|^|',$txt_x);
		$txt_y_arr = explode('|^|',$txt_y);
		$font_arr = explode('|^|',$font);
		
				
		//要裁剪图像的宽高
		$width=$area_w;
		$height=$area_h;
		if(!$width || !$height){
			echo 1;
			exit;
		}

		//要裁剪图像的顶点位置
		$img_x=$area_x;
		$img_y=$area_y;

		//获取原图像的尺寸
		list($src_width, $src_height,$type) = getimagesize(RES_ROOT.$imgpath);
		
		if($width!=612){
			if($src_width<$width || $src_height<$height){
				echo 2;
				exit;
			}
		}
		
		//更新数据库中图片加上的文字
		$share_data = array();
		$share_data['share_id'] = $shareid;
		$share_data['edit_text'] = $txt;
		$result = D("Share")->save($share_data);
		//判断图片类型是否为jpg类型
		if($type != 2){ 
			echo 3;
			exit;
		}
		$src_radio = $src_width/$src_height;
		$radio = $width/$height;
		if($radio >= $src_radio){
			$newsrc_width = $width;
			$newsrc_height = $newsrc_width/$src_radio;
		}else{
			$newsrc_height = $height;
			$newsrc_width = $newsrc_height*$src_radio;
		}
		//裁剪从客户端获取到的尺寸的图片
		$im = @imagecreatefromjpeg(RES_ROOT.$imgpath);
		$sizeim=imagecreatetruecolor($newsrc_width,$newsrc_height);
		$tumb=imagecopyresampled ( $sizeim, $im, 0, 0, 0, 0, $newsrc_width, $newsrc_height, $src_width , $src_height);

		if(!$tumb){
			echo 4;
			exit;
		}

		$newim=imagecreatetruecolor($width,$height);
		$copy=imagecopy ( $newim, $sizeim, 0, 0, $img_x, $img_y, $width, $height );

		if(!$copy){
			echo 5;
			exit;
		}
	   
		function getfontPath($font){
			$docloc = RES_ROOT."tpl/strends/font/";
			if( $font=='宋体' ) {
				$font = $docloc."simsun.ttc";
			}else if( $font=='Microsoft JhengHei' ){
				$font = $docloc."zmsjh.ttf";
			}else if( $font=='Microsoft JhengHei Bold' ){
				$font = $docloc."zmsjhbd.ttf";
			}else if( $font=='黑体' ){
				$font = $docloc."simhei.ttf";
			}else if( $font=='微软雅黑' ){
				$font = $docloc."msyh.ttf";
			}else if( $font=='微软雅黑 Bold' ){
				$font = $docloc."msyhbd.ttf";
			}else if( $font=='幼圆' ){
				$font = $docloc."SIMYOU.TTF";
			}else if( $font=='方正粗宋简' ){
				$font = $docloc."fzcsjt.TTF";
			}else if( $font=='时尚中黑简体' ){
				$font = $docloc."sszhjt.ttf";
			}else if( $font=='方正细等线_GBK' ){
				$font = $docloc."simfzxd.ttf";
			}else if( $font=='方正报宋简体' ){
				$font = $docloc."fzbsjt.TTF";
			}else if( $font=='方正粗倩简体' ){
				$font = $docloc."fzcqjt.TTF";
			}else if( $font=='汉仪中等线简' ){
				$font = $docloc."simhanyi.TTF";
			}else if( $font=='Candara Bold' ){
				$font = $docloc."Candarab.ttf";
			}else if( $font=='Candara Italic' ){
				$font = $docloc."Candarai.ttf";
			}else if( $font=='Candara Bold Italic' ){
				$font = $docloc."Candaraz.ttf";
			}else if( $font=='Candara' ){
				$font = $docloc."Candara.ttf";
			}else if( $font=='Century Gothic Bold Italic' ){
				$font = $docloc."century gothic BOLD.ttf";
			}else if( $font=='Freestyle Script' ){
				$font = $docloc."FREESCPT.TTF";
			}else if( $font=='Century Gothic' ){
				$font = $docloc."GOTHIC_0.TTF";
			}else if( $font=='Century Gothic Bold' ){
				$font = $docloc."GOTHICB_0.TTF";
			}else if( $font=='century Gothic Italic' ){
				$font = $docloc."GOTHICI_0.TTF";
			}else if( $font=='Blackadder ITC' ){
				$font = $docloc."ITCBLKAD.TTF";
			}else if( $font=='Kunstler Script' ){
				$font = $docloc."KUNSTLER.TTF";
			}else if( $font=='Microsoft Sans Serif' ){
				$font = $docloc."micross.ttf";
			}else if( $font=='Stencil' ){
				$font = $docloc."STENCIL.TTF";
			}else if( $font=='隶书'){
				$font = $docloc."SIMLI.TTF";
			}else if( $font=='Microsoft JhengHei Bold'){
				$font = $docloc."msjhbd.ttf";
			}else if( $font=='Microsoft JhengHei'){
				$font = $docloc."msjh.ttf";
			}else{
				$font = $docloc."zmsjhbd.ttf";
			}
			return $font;
		}

		function Hex2RGB( $hexColor ){ //十六进制转GRB
			$color = str_replace('#','' , $hexColor);
			if (strlen($color) > 3) {
				$rgb = array(
					'r' => hexdec(substr($color, 0, 2)),
					'g' => hexdec(substr($color, 2, 2)),
					'b' => hexdec(substr($color, 4, 2))
				);
			} else {
				$color = str_replace('#','' , $hexColor);
				$r = substr($color, 0, 1) . substr($color, 0, 1);
				$g = substr($color, 1, 1) . substr($color, 1, 1);
				$b = substr($color, 2, 1) . substr($color, 2, 1);
				$rgb = array(
					'r' => hexdec($r),
					'g' => hexdec($g),
					'b' => hexdec($b)
				);
			}
			return $rgb;
		}

		function fontPX($font_size, $angle, $font, $txt){ //得到字符串高宽度
			$testbox = imagettfbbox($font_size, $angle, $font, $txt);
			$s['width'] = abs($testbox[2]-$testbox[0]);
			$s['height'] = abs($testbox[1]-$testbox[7]);
			return $s;
		}
		
		function isIncludeChinse($str){	//判断字母或数字的UTF-8编码的长度和其ASCII编码是否一致
			if(strlen(mb_convert_encoding($str,"utf-8"))==strlen(mb_convert_encoding($str,""))){
				return false;
			}else{ 
				return true;
			}
		}

	  for($t=0;$t<4;$t++){	//循环四组文字
		  if($txt_arr[$t]!=''){
			  $colorArr = Hex2RGB($font_color_arr[$t]);	//颜色十六进制转RGB
			  $color = imagecolorallocate($newim, $colorArr['r'], $colorArr['g'], $colorArr['b']);

			  $lineArr = explode("\n",$txt_arr[$t]);
			  for($j=0;$j<count($lineArr);$j++){	//循环每行文字
				  $px_h = fontPX($font_size_arr[$t], 0, getfontPath($font_arr[$t]), $lineArr[$j]);	//一行字的高度
				  if($px_h['height']==0) $px_h['height']=$font_size_arr[$t];
				  if($j==0){//第一行文字
					  if($linespacing_arr[$t]==15 && $font_size_arr[$t]==12 ){
						  $line_y = ceil($txt_y_arr[$t]+$font_size_arr[$t]);//第一行的y
					  }else{
						  $line_y = ceil($txt_y_arr[$t]+$linespacing_arr[$t]/1.15);//第一行的y
					  }
				  }else{
					  $line_y += ceil($px_h['height']+$linespacing_arr[$t]-$font_size_arr[$t]*1.1);	//第二行 第三行 .... 的y
				  }

				  if($spacing_arr[$t]=='0'){	//没有设置行间距
					  imagettftext($newim, $font_size_arr[$t], 0, $txt_x_arr[$t], $line_y, $color, getfontPath($font_arr[$t]), $lineArr[$j]);
				  }else{
					  $c = mb_strlen($lineArr[$j], 'utf-8');	//一行有几个字
					  $font_x_b = 0;
					  $charArr=array(//(向前移或向后移,字后留的距离,向上或向下移)
						  '自'=>array(0,0.25,0),
						  '己'=>array(0,0.08,0),
						  '·'=>array(-0.1,0.08,0),
						  '“'=>array(0,0.6,0),
						  '^'=>array(-0.25,0,0),
						  '”'=>array(0.1,0.6,0),
						  '的'=>array(0,0.2,0),
						  'A'=>array(0,-0.3,0),
						  'B'=>array(0,0.01,0),
						  'Z'=>array(0.2,-0.2,0),
						  'z'=>array(0.02,-0.2,0),
						  'J'=>array(0.02,-0.2,0),
						  'K'=>array(0.05,-0.1,0),
						  ')'=>array(0.02,0,0),
						  'I'=>array(0.02,-0.02,0),
						  'Y'=>array(-0.02,-0.02,0),
					  );
					  for($i=0;$i<$c;$i++){	//循环每个文字
						  $current = mb_substr($lineArr[$j], $i, 1, 'utf-8');
						  if($i==0){//每行第一个字
							  $font_x = $txt_x_arr[$t];	//间距
						  }else{
							  $prev = mb_substr($lineArr[$j], $i-1, 1, 'utf-8'); 	//前一个字
							  $prev_w = fontPX($font_size_arr[$t], 0, getfontPath($font_arr[$t]), $prev);		//前一个字的宽度
							  if($prev_w['width']==0) $prev_w['width']=$font_size_arr[$t];
							  $font_x += $prev_w['width']+$spacing_arr[$t];
						  }
						  if(isset($charArr[$current])){
							  $font_x += ceil($font_size_arr[$t]*$charArr[$current][0]);	//单个字向前或向后
							  $font_x_b = ceil($font_size_arr[$t]*$charArr[$current][1]);	//单个字后留多少像素
							  $line_y += ceil($font_size_arr[$t]*$charArr[$current][2]);	//单个字上下偏移
						  }else{
							  $font_x_b = 0;
						  }
						  imagettftext($newim, $font_size_arr[$t], 0, $font_x, $line_y, $color, getfontPath($font_arr[$t]), $current);
						  $font_x += $font_x_b;
					  }
				  }
			  }
		  }
	  }
		
		$newPic = str_replace('.jpg','_thumb_'.$width.'x'.$height.'.jpg',$imgpath);
		if($newPic == $imgpath){
			exit('生成新裁剪图片路径错误');
		}
		
		imagejpeg($newim,RES_ROOT.$newPic,100);
		echo '|^|'.$newPic.'|'.$width.'|'.$height.'|'.$albumid.'|'.$shareid;
		
		//createFuzzyGraph(RES_ROOT.$newPic, 1, 5);    //生成模糊图
		//imagedestroy($im);
		imagedestroy($newim);
		imagedestroy($sizeim);	
	}
	//采集图片
	public function caitu(){
		$imgs = $_GET['imgUrl'];
		$pageUrl = $_GET['pageUrl'];
		//$img_list = explode(",",$imgs);
		//$count_img = count($img_list);
		$tag_cate=D('GoodsCategory')->where('parent_id=0')->order('sort')->field('cate_id,cate_name')->findAll();
		$tag_list = array();
		foreach($tag_cate as $k=>$v){
			$tag_list[$v['cate_id']] = D('GoodsCategory')->where('parent_id='.$v['cate_id'])->order('sort')->field('cate_id,cate_name')->findAll();
		}
		$category_list = D("AlbumCategory")->order('sort asc,id asc')->findAll();
		$this->assign("category_list",$category_list);
		$this->assign("tag_list",$tag_list);
		$this->assign('imgs',$imgs);
		$this->assign('pageurl',$pageUrl);
		
		$this->display ();		
	}
	public function caitu_insert(){
		$model = D ('Album');
		
		if (false === $data = $model->create ()) {
			$this->error ( $model->getError () );
		}
		$imgs = $_POST['imgs'];
		$purl = $_POST['purl'];
		$img_list = explode(",",$imgs);
		$data['img_count'] = count($img_list);
		$tag_list = $_POST['tag_list'];
		$data['create_time'] = time();
		$data['uid'] = $_SESSION['strends_shop_share'];
		// 更新数据
		$albumid=$model->data($data)->add();
		$tag_list = $_POST['tag_list'];
		foreach($tag_list as $v){
			$tag_data['tag_id'] = $v;
			$tag_data['album_id'] = $albumid;
			D('album_goods')->add($tag_data);
		}
		$share_list = array();
		$i=0;
		foreach($img_list as $v){
			$img= $v;
			$imgname = substr( $img , strrpos($img , '/')+1 );
			$id_path = getDirsById($albumid);
			$dir = RES_ROOT.'public/upload/share/'.$id_path.'/';
			if(!file_exists($dir)){
				createFolder($dir);
			}
			$filename = $dir.$imgname;
			copy($img,$filename);
			
			$data = array();
			$data['index_img'] = 'public/upload/share/'.$id_path.'/'.$imgname;
			$data['rec_id'] = $albumid;
			$data['create_time'] = time();
			$model = D ('Share');
			$shareid=$model->data($data)->add();
			$album_share = array();
			$album_share['album_id'] = $albumid;
			$album_share['share_id'] = $shareid;
			D('AlbumShare')->data($album_share)->add();
			$share_list[$i]['share_id'] = $shareid;
			$share_list[$i]['index_img'] = 'public/upload/share/'.$id_path.'/'.$imgname;
			$share_list[$i]['title'] = '';
			$share_list[$i]['content'] = '';
			$i++;
		}
		
		if (false !== $albumid)
		{
			$this->assign('albumid',$albumid);
			$this->assign('share_list',$share_list);
			$this->display('Album/uploadpic');
		}
	}
}

/**
 * 根据ID划分目录
 * @return string
 */
function getDirsById($id)
{
	$id = sprintf("%011d", $id);
	$dir1 = substr($id, 0, 3);
	$dir2 = substr($id, 3, 3);
	$dir3 = substr($id, 6, 3);
	$dir4 = substr($id, -2);
	return $dir1.'/'.$dir2.'/'.$dir3.'/'.$dir4;
}
function createFolder($path){
    if(!file_exists($path)){
        createFolder(dirname($path));
        mkdir($path);
    }
}
function get_name($pic_item,$key)    
{         
	
	$img_data = @file_get_contents($pic_item);
	if(!empty($img_data)){
		$mtime = date('Ym');
		$dtime = date('d');
		$dir = RES_ROOT.'public/upload/images/'.$mtime.'/'.$dtime.'/';
		
		if(!file_exists($dir)){
			mkdir(RES_ROOT.'public/upload/images/'.$mtime.'/'.$dtime.'/');
		}
		
		$img_index = 'public/upload/images/'.$mtime.'/'.$dtime.'/'.time().$key.'.jpg';
		$img_size = @file_put_contents(RES_ROOT.$img_index, $img_data);
		return PIC_ROOT.$img_index; 
	}else{
		return;   
	}      
	 
}
?>